import { Button, Input, App } from 'antd'
import { ImportantEditModal } from '@/desktop/components'
import services from '@/services'
import type { AccountGroup } from '@/services/features/accounts'

export default function EditGroup(props: {
  group?: AccountGroup // 指定则为编辑，否则为新建
  visible: boolean
  onFinish: () => void
}) {
  const { group, visible, onFinish } = props
  return <ImportantEditModal
    title={group ? '编辑账号分组' : '新建账号分组'}
    open={visible}
    onCancel={onFinish}
    width="500px"
  >
    {visible ? <Editing group={group} onFinish={onFinish} /> : null}
  </ImportantEditModal>
}

function Editing(props: { group?: AccountGroup; onFinish: () => void }) {
  const { message } = App.useApp()
  const { group, onFinish } = props

  const [name, setName] = useState(group?.name ?? '')
  const [msg, setMsg] = useState('')
  const [submitting, setSubmitting] = useState(false)

  function onChange(e: React.ChangeEvent<HTMLInputElement>) {
    setMsg('')
    setName(e.target.value)
  }

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setMsg('')
    if (name === '') {
      setMsg('请输入分组名称')
      return
    }

    setSubmitting(true)
    const res = !group
      ? await services.features.accounts.addGroup(name)
      : await services.features.accounts.updateGroup({ ...group, name })
    setSubmitting(false)

    const type = !group ? '新建' : '保存'
    if (res === true) {
      void message.success(`${type}成功！`)
      onFinish()
    } else {
      void message.warning(`${type}失败：${res}`)
    }
  }

  return <form onSubmit={onSubmit}>
    <main>
      <div css={s.row}>
        <label>分组名称：</label>
        <Input placeholder="在此输入分组名称" maxLength={15} value={name} onChange={onChange} />
      </div>
      <div css={s.msg}>{msg}</div>
    </main>

    <footer>
      <Button onClick={() => onFinish()}>取消</Button>
      <Button loading={submitting} type="primary" htmlType="submit">
        保存
      </Button>
    </footer>
  </form>
}

const s = {
  row: css`
    align-items: center;
    display: flex;
    label {
      width: 75px;
      flex-shrink: 0;
    }
  `,
  msg: css`
    color: red;
    font-size: 12px;
    height: 20px;
    margin-left: 75px;
    margin-top: 6px;
  `,
}
